﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class UserRoleController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Infrastructure.Crosscutting.Authorize.IUserRoleService userRoleService;

        Infrastructure.Crosscutting.Authorize.IUserService userService;

        Infrastructure.Crosscutting.Authorize.IRoleService roleService;

        public UserRoleController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Infrastructure.Crosscutting.Authorize.IUserRoleService userRole,
            Infrastructure.Crosscutting.Authorize.IUserService user,
            Infrastructure.Crosscutting.Authorize.IRoleService role)
            : base(work)
        {
            if (userRole == null)
            {
                throw new ArgumentNullException("userRoleService is null");
            }
            if (user == null)
            {
                throw new ArgumentNullException("userService is null");
            }
            if (role == null)
            {
                throw new ArgumentNullException("roleService is null");
            }
            userRoleService = userRole;
            userService = user;
            roleService = role;
        }

        public ViewResult Index(int? id)
        {
            var model = this.GetUserRoleTrueState();
            if (id.HasValue)
            {
                model = model.Where(e => e.UserId == id);
                ViewBag.user = userService.GetUserModelById(id ?? 0);
            }
            return View(model.ToList());
        }

        [GridAction]
        public JsonResult AjaxIndex(int? id, string searchKey)
        {
            var data = this.GetUserRoleTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.RoleName.Contains(searchKey.Trim()));
            }
            if (id.HasValue)
            {
                data = data.Where(e => e.UserId == id);
            }
            data = data.OrderByDescending(e => e.Id);
            var model = new GridModel<Infrastructure.Crosscutting.Authorize.Dto.UserRoleDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var model = userRoleService.Get(id);
            if (model != null && model.Id > 0)
            {
                userRoleService.DeleteTrue(model, this.WorkContext.CurrentUser);
            }
            var data = this.GetUserRoleTrueState();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = userRoleService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            var model = userRoleService.GetDto(id);
            return View(model);
        }

        [HttpPost]
        public JsonResult Edit(Infrastructure.Crosscutting.Authorize.Dto.UserRoleDto dto)
        {
            var res = false;
            var message = "";
            var model = userRoleService.Get(dto.Id);
            if (dto.Id > 0 && model != null)
            {
                var hasRole = userRoleService.GetList()
                    .Where(e => e.UserId == dto.UserId && e.RoleId == dto.RoleId).Any();
                if (!hasRole)
                {
                    model.RoleId = dto.RoleId;
                    if (userRoleService.Modify(model, this.WorkContext.CurrentUser))
                    {
                        res = true;
                    }
                    else
                    {
                        message = "修改失败";
                    }
                }
                else
                {
                    message = "该用户已经有这个角色了";
                }
            }
            else
            {
                message = "没的找到提交的用户以及角色信息";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }


        public JsonResult Search(int id, string term)
        {
            var data = this.GetUserRoleTrueState().Where(e => e.UserId == id)
            .Where(e => e.RoleName.Contains(term.Trim()))
            .OrderByDescending(e => e.Id).Select(e => e.RoleName).Distinct().Take(10);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #region add user role

        [HttpGet]
        public ViewResult Add(int id)
        {
            ViewBag.user = userService.GetUserModelById(id);
            var userRoleIdList = this.GetUserRoleTrueState()
                .Where(e => e.UserId == id).Select(e => e.RoleId);
            var model = roleService.GetList().Where(e => !userRoleIdList.Contains(e.Id))
                .OrderByDescending(e => e.Id).ToDto();
            return View(model);
        }

        [HttpPost]
        public JsonResult AjaxAdd(int id, string searchKey)
        {
            var userRoleIdList = this.GetUserRoleTrueState()
                .Where(e => e.UserId == id).Select(e => e.RoleId);
            var data = roleService.GetList().Where(e => !userRoleIdList.Contains(e.Id))
                .OrderByDescending(e => e.Id).ToDto();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey.Trim()));
            }
            var model = new GridModel<Domain.Dto.RoleDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult MulAdd(FormCollection add)
        {
            var userIdStr = add["UserId"];
            int userId = 0;
            int.TryParse(userIdStr, out userId);
            var res = false;
            var message = "";
            if (userId > 0)
            {
                try
                {
                    var selecteList = add.GetValues("selectRow");
                    var addIdList = selecteList.ToIntList();
                    foreach (var item in addIdList)
                    {
                        var temp = new Domain.Entity.UserRole();
                        temp.AddTime = System.DateTime.Now;
                        temp.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                        temp.RoleId = item;
                        temp.SortNum = 0;
                        temp.State = true;
                        temp.UserId = userId;
                        userRoleService.Add(temp, this.WorkContext.CurrentUser);
                        res = true;
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            else
            {
                message = "添加角色失败了哦！！！";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message });
        }

        public JsonResult SearchAdd(int id, string term)
        {
            var userRoleIdList = this.GetUserRoleTrueState()
               .Where(e => e.UserId == id).Select(e => e.RoleId);
            var data = roleService.GetList().Where(e => !userRoleIdList.Contains(e.Id))
                .OrderByDescending(e => e.Id).AsQueryable();
            if (!string.IsNullOrEmpty(term))
            {
                data = data.Where(e => e.Name.Contains(term.Trim()));
            }
            var res = data.OrderByDescending(e => e.Id).Select(e => e.Name).Distinct().Take(10);
            return Json(res, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region util

        protected IQueryable<Infrastructure.Crosscutting.Authorize.Dto.UserRoleDto> GetUserRoleTrueState()
        {
            var data = userRoleService.GetListDto().Where(e => e.State == true)
                .OrderByDescending(e => e.Id);
            return data;
        }

        #endregion
    }
}
